//
//  HomePageCommentView.m
//  ShowYork
//
//  Created by hxh on 2020/11/19.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageCommentView.h"
#import "HomePageCommentListViewController.h"
#import "HomePageReplyListViewController.h"
#import "HomePageCommentListCell.h"
#import "HomePageReplyListCell.h"
#import "HomePageCommentFollowCell.h"
#import "GKLoadingView.h"
#import "XHHomePageFooter.h"
@interface HomePageCommentView ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextViewDelegate,HomePageCommentListCellDelegate>

@property (nonatomic,strong)UIView *containView;
@property (nonatomic,strong)UIView *bottomView;

@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)UILabel *commentCountLb;

@property (nonatomic,strong)UIView *bottomTFView;
@property (nonatomic,strong)UIImageView *bottomIcon;
@property (nonatomic,strong)UIButton *bottomButton;
@property (nonatomic,strong)UILabel *bottomPlaceLb;

@property (nonatomic,strong)UIScrollView *scrollView;



@property (nonatomic,strong)UIView *coverView;
@property (nonatomic,strong)UIView *inputView;
@property (nonatomic,strong)UIView *inputContainView;
@property (nonatomic,strong)UILabel *inputSendLb;
@property (nonatomic,strong)UIButton *inputSendBtn;
@property (nonatomic,strong)UIButton *aboutBtn;
@property (nonatomic,strong)UIImageView *aboutIcon;
@property (nonatomic,strong)UITextView *inputTextView;
@property (nonatomic,strong)UILabel *inputPlaceLb;

@property (nonatomic,strong)UIView *resultView;
@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)UILabel *headerResultLb;
@property (nonatomic,strong)GKLoadingView *headerLoadingView;
@property (nonatomic,strong)UIView *resultRefreshHeaderView;


@property (nonatomic,strong)NSMutableArray *userArray;

@property (nonatomic,assign)BOOL isSearch;

@property (nonatomic,assign)BOOL isDraging;

@property (nonatomic,assign)NSInteger location;

@property (nonatomic,assign)NSRange insertRang;

@property (nonatomic,strong)NSMutableDictionary *locationDict;

@property (nonatomic,copy)NSString *searchKey;

@property (nonatomic,strong)RPBaseViewController *bindVC;

@property (nonatomic,strong)HomePageCommentListViewController *commentListVC;

@property (nonatomic,strong)HomePageReplyListViewController *replyListVC;

@property (nonatomic,assign)XHCommentType type;

@property (nonatomic,strong)NSNumber *commentId;

@property (nonatomic,strong)UIButton *coverBtn;

@property (nonatomic,strong)UIButton *dismissBtn;

@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIImageView *backImgView;

@property (nonatomic,strong)UIButton *removeBtn;

@property (nonatomic,strong)UIImageView *removeImgView;

@property (nonatomic,weak)id<HomePageCommentViewDelegate>delegate;

@property (nonatomic,assign)XHPageDetailPlatformType platformType;

@property (nonatomic,strong)NSNumber *platformId;

@property (nonatomic,strong)NSNumber *lastReplyId;

@property (nonatomic,strong)NSNumber *lastCommentId;

@property (nonatomic,assign)NSInteger commentCount;

@property (nonatomic,assign)NSRange lastSelectedRange;

@property (nonatomic,assign)BOOL isUpdate;

@property (nonatomic,copy)NSString *lastText;

@property (nonatomic,assign)BOOL isChinese;

@property (nonatomic,assign)BOOL isDelete;

@property (nonatomic,assign)NSRange markRangeLoc;

@property (nonatomic,assign)BOOL isDictation;

@property (nonatomic,assign)NSRange dictationRange;

@property (nonatomic,copy)NSString *lang;

@end

@implementation HomePageCommentView


- (NSMutableArray *)userArray{
    if (!_userArray) {
        _userArray = [NSMutableArray array];
    }
    return _userArray;
}
- (NSMutableDictionary *)locationDict{
    if (!_locationDict) {
        _locationDict = [NSMutableDictionary dictionary];
    }
    return _locationDict;
}

- (instancetype)initWithPlatformId:(NSNumber *)platformId platformType:(XHPageDetailPlatformType)type showCommentId:(NSNumber *)commentId showReplyId:(NSNumber *)replyId{
    if (self = [super init]) {
        self.platformId = platformId;
        self.platformType = type;
       
        self.lastCommentId = commentId;
        self.lastReplyId = replyId;
    
        [self setUI];
        [self registNote];
    }
    return self;
}

- (void)setUI{
    
    self.frame = CGRectMake(0,0, kScreenW,kScreenH);
    
    self.backgroundColor = RGBA(0, 0, 0, 0.5);
    
    self.dismissBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    [self.dismissBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.dismissBtn];
    
    
    self.containView = [[UIView alloc]init];
    self.containView.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH * 0.8);
    self.containView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.containView];
    
    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(216, 216, 216, 1);
    [self.containView addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containView).offset(40);
        make.left.right.equalTo(self.containView);
        make.height.mas_equalTo(0.5);
    }];
    self.commentCountLb = [[UILabel alloc]init];
    self.commentCountLb.textColor = C35;
    self.commentCountLb.font = [UIFont boldSystemFontOfSize:14];
    [self.containView addSubview:self.commentCountLb];
    [self.commentCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.containView);
        make.top.equalTo(self.containView);
        make.height.mas_equalTo(40);
    }];
    
    self.bottomView = [[UIView alloc]init];
    [self.containView addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.right.equalTo(self.containView);
        make.bottom.equalTo(self.containView).offset(-GK_SAVEAREA_BTM);
    }];
    
    self.bottomIcon = [[UIImageView alloc]init];
    self.bottomIcon.image = [UIImage imageNamed:@"defaut_header"];
    self.bottomIcon.layer.cornerRadius = 16;
    self.bottomIcon.layer.masksToBounds = YES;
    [self.bottomView addSubview:self.bottomIcon];
    [self.bottomIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomView);
        make.left.equalTo(self.bottomView).offset(16);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    self.bottomTFView = [[UIView alloc]init];
    self.bottomTFView.backgroundColor =  RGBA(248, 248, 248, 248);
    self.bottomTFView.layer.cornerRadius = 16;
    self.bottomTFView.layer.masksToBounds = YES;
    [self.bottomView addSubview:self.bottomTFView];
    [self.bottomTFView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(32);
        make.centerY.equalTo(self.bottomView);
        make.left.equalTo(self.bottomIcon.mas_right).offset(12);
        make.right.equalTo(self.bottomView).offset(-16);
    }];
    
    
    self.bottomButton = [[UIButton alloc]init];
    [self.bottomButton addTarget:self action:@selector(beginTF) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomTFView addSubview:self.bottomButton];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomTFView).offset(12);
        make.right.equalTo(self.bottomTFView).offset(-12);
        make.top.bottom.equalTo(self.bottomTFView);
    }];
    
    self.bottomPlaceLb = [[UILabel alloc]init];
    self.bottomPlaceLb.text = @"快来发布你的评论…";
    self.bottomPlaceLb.textColor = C153;
    self.bottomPlaceLb.font = font(14);
    [self.bottomTFView addSubview:self.bottomPlaceLb];
    [self.bottomPlaceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomTFView);
        make.left.equalTo(self.bottomTFView).offset(12);
    }];
    
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.scrollEnabled = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    [self.containView addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.containView);
        make.top.equalTo(self.line.mas_bottom);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    self.scrollView.contentSize = CGSizeMake(kScreenW * 2, 0);
    

    self.backImgView = [[UIImageView alloc]init];
    self.backImgView.image = [UIImage imageNamed:@"home_comment_delete_tag"];
    [self.containView addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.commentCountLb);
        make.left.equalTo(self.containView).offset(10);
    }];
    
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.containView addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.containView);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(60);
    }];
    
    self.removeImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_comment_back_tag"]];
    [self.containView addSubview:self.removeImgView];
    [self.removeImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.commentCountLb);
        make.left.equalTo(self.containView).offset(10);
    }];
    self.removeBtn = [[UIButton alloc]init];
    [self.removeBtn addTarget:self action:@selector(removeMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.containView addSubview:self.removeBtn];
    [self.removeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.containView);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(60);
    }];
    self.removeImgView.hidden = YES;
    self.removeBtn.hidden = YES;
    
    
    
    self.coverView = [[UIView alloc]init];
    self.coverView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.coverView.backgroundColor = RGBA(0, 0, 0, 0.5);
    [self addSubview:self.coverView];
    
    self.coverBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    [self.coverBtn addTarget:self action:@selector(coverMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.coverView addSubview:self.coverBtn];
    
    self.inputView = [[UIView alloc]init];
    self.inputView.frame = CGRectMake(0,kScreenH, kScreenW, kScreenW * 0.36);
    self.inputView.backgroundColor = [UIColor whiteColor];
    [self.coverView addSubview:self.inputView];
    
    self.coverView.hidden = YES;
    
    self.inputContainView = [[UIView alloc]init];
    self.inputContainView.backgroundColor = RGBA(240, 240, 240, 1);
    self.inputContainView.layer.cornerRadius = 10;
    self.inputContainView.layer.masksToBounds = YES;
    [self.inputView addSubview:self.inputContainView];
    [self.inputContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputView).offset(12);
        make.left.equalTo(self.inputView).offset(16);
        make.right.equalTo(self.inputView).offset(-60);
        make.bottom.mas_equalTo(self.inputView).offset(-40);
    }];
    
    self.inputPlaceLb = [[UILabel alloc]init];
    self.inputPlaceLb.text = @"快来发布你的评论…";
    self.inputPlaceLb.textColor = C153;
    self.inputPlaceLb.font = font(14);
    [self.inputView addSubview:self.inputPlaceLb];
    [self.inputPlaceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.inputView).offset(20);
        make.top.equalTo(self.inputView).offset(19);
    }];
    
    self.inputSendLb = [[UILabel alloc]init];
    self.inputSendLb.text = @"发送";
    self.inputSendLb.textColor = [RPAppManager themColor];
    self.inputSendLb.font = [UIFont boldSystemFontOfSize:14];
    self.inputSendLb.textAlignment = NSTextAlignmentCenter;
    [self.inputView addSubview:self.inputSendLb];
    [self.inputSendLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.inputContainView.mas_right);
        make.right.equalTo(self.inputView);
        make.top.equalTo(self.inputPlaceLb);
    }];
    
    self.inputSendBtn = [[UIButton alloc]init];
    [self.inputSendBtn addTarget:self action:@selector(sendMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.inputView addSubview:self.inputSendBtn];
    
    [self.inputSendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.inputContainView.mas_right);
        make.right.equalTo(self.inputView);
        make.top.equalTo(self.inputContainView);
        make.height.mas_equalTo(40);
    }];
    
    self.aboutIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"commone_@_tag"]];
    [self.inputView addSubview:self.aboutIcon];
    [self.aboutIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputContainView.mas_bottom).offset(11);
        make.bottom.equalTo(self.inputView).offset(-12);
        make.left.equalTo(self.inputView).offset(20);
    }];
    self.aboutBtn = [[UIButton alloc]init];
    [self.aboutBtn addTarget:self action:@selector(aboutMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.inputView addSubview:self.aboutBtn];
    [self.aboutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(self.inputView);
        make.top.equalTo(self.inputContainView.mas_bottom);
        make.width.mas_equalTo(60);
    }];
    
    self.inputTextView = [[UITextView alloc]init];
    self.inputTextView.backgroundColor = [UIColor clearColor];
    self.inputTextView.delegate = self;
    self.inputTextView.textColor = RGBA(51, 51, 51, 1);
    self.inputTextView.font = font(14);
    
    [self.inputView addSubview:self.inputTextView];
    [self.inputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.inputContainView);
    }];
    
    self.resultView = [[UIView alloc]init];
    self.resultView.frame = CGRectMake(0,CGRectGetMinY(self.inputView.frame) - kScreenW * 0.45, kScreenW, kScreenW * 0.45);
    self.resultView.backgroundColor = [UIColor whiteColor];
    self.resultView.hidden = YES;
    [self.coverView addSubview:self.resultView];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW,kScreenW * 0.45) style:UITableViewStyleGrouped];
    if (@available(iOS 11.0, *)) {
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight=0;
            _tableView.contentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.resultView addSubview:self.tableView];

    self.resultRefreshHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 55)];
    
    self.headerLoadingView = [GKLoadingView loadingViewWithFrame:CGRectMake(16,16,20, 20) style:GKLoadingStyleIndeterminateMask];
    self.headerLoadingView.radius = 10;
    self.headerLoadingView.lineWidth = 1;

    [self.resultRefreshHeaderView addSubview:self.headerLoadingView];

    [self.headerLoadingView startLoading];

    self.headerResultLb = [[UILabel alloc]initWithFrame:CGRectMake(55, 0, kScreenW - 55, 55)];
    self.headerResultLb.text = @"搜索中...";
    self.headerResultLb.textColor = C153;
    self.headerResultLb.font = font(14);

    [self.resultRefreshHeaderView addSubview:self.headerResultLb];

    [self.resultView addSubview:self.resultRefreshHeaderView];
    
    self.tableView.mj_footer = [XHHomePageFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    if (self.lastCommentId.intValue != 0) {
        self.commentListVC = [[HomePageCommentListViewController alloc]initWithPostId:self.platformId commentId:self.lastCommentId];
    }else{
        self.commentListVC = [[HomePageCommentListViewController alloc]initWithPostId:self.platformId];
    }

    [self.scrollView addSubview:self.commentListVC.view];
    [self.commentListVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.width.equalTo(self.scrollView);
        make.leading.mas_equalTo(self.scrollView.mas_leading);
    }];
    if (self.lastReplyId.intValue != 0) {
        self.replyListVC = [[HomePageReplyListViewController alloc]initWithLastReplyId:self.lastReplyId];
    }else{
        self.replyListVC = [[HomePageReplyListViewController alloc]init];

    }
    [self.scrollView addSubview:self.replyListVC.view];
    [self.replyListVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.width.equalTo(self.scrollView);
        make.leading.mas_equalTo(self.commentListVC.view.mas_trailing);
    }];
    
    __weak typeof(self)weakSelf = self;
    self.commentListVC.sendReplyComment = ^(NSNumber *commentId) {
        weakSelf.commentId = commentId;
        weakSelf.type = XHCommentTypeReply;
        weakSelf.inputPlaceLb.hidden = NO;
        weakSelf.inputPlaceLb.text = @"回复评论";
        [weakSelf showInputTextView];
    };
    
    self.commentListVC.showMoreReplyMessage = ^(HomePageCommentItemModel *itemModel) {
        weakSelf.inputPlaceLb.hidden = NO;
        weakSelf.backImgView.hidden = YES;
        weakSelf.backBtn.hidden = YES;
        
        weakSelf.removeImgView.hidden = NO;
        weakSelf.removeBtn.hidden = NO;
        
        [weakSelf.replyListVC requestDataWithCurrentModel:itemModel];
        [weakSelf.scrollView setContentOffset:CGPointMake(kScreenW, 0) animated:YES];
        weakSelf.commentId = itemModel.id;
        // 修改状态
        weakSelf.type = XHCommentTypeReply;
        weakSelf.inputPlaceLb.text = @"回复评论";
        weakSelf.bottomPlaceLb.text = @"回复评论";
        // 设置标题
        weakSelf.commentCountLb.text = @"";
    };
    self.commentListVC.updateCommentCount = ^(NSInteger commentCount) {
        weakSelf.commentCount = commentCount;
        NSString *title = @"";
        if (commentCount >= 10000) {
            NSInteger count = commentCount;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"%@w条评论",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"%ld条评论",(long)commentCount];
        }
        
        weakSelf.commentCountLb.text = title;
    };
    self.replyListVC.showSendCommentReply = ^(NSNumber * _Nonnull commentId) {
        weakSelf.type = XHCommentTypeReply;
        weakSelf.commentId = commentId;
        [weakSelf showInputTextView];
    };
    
    self.replyListVC.showNavTitle = ^(NSString * _Nonnull navTitle) {
        weakSelf.commentCountLb.text = navTitle;
    };
    self.replyListVC.deleteComment = ^{
        weakSelf.removeBtn.hidden = YES;
        weakSelf.removeImgView.hidden = YES;
        
        weakSelf.backBtn.hidden = NO;
        weakSelf.backImgView.hidden = NO;
        
        [weakSelf.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
        weakSelf.type = XHCommentTypeComment;
        weakSelf.inputPlaceLb.text = @"快来发布你的评论…";
        weakSelf.bottomPlaceLb.text = @"快来发布你的评论…";
        
        weakSelf.commentCount -=1;
        NSString *title = @"";
        if (weakSelf.commentCount >= 10000) {
            NSInteger count = weakSelf.commentCount;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"%@w条评论",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"%ld条评论",(long)weakSelf.commentCount];
        }
        weakSelf.commentCountLb.text = title;
    };
    UserInfoModel *userInfo = [UserInfoModel userInfo];
    if (userInfo.imagePath.length == 0) {
        if (userInfo.sex.intValue == 0) {
            self.bottomIcon.image = [UIImage imageNamed:@"defaut_header"];
        }else if (userInfo.sex.intValue == 1){
            self.bottomIcon.image = [UIImage imageNamed:@"common_boy_tag"];
        }else{
            self.bottomIcon.image = [UIImage imageNamed:@"common_girl_tag"];
        }
    }else{
        [self.bottomIcon sd_setImageWithURL:[NSURL URLWithString:userInfo.imagePath] placeholderImage:[UIImage imageNamed:@"defaut_header"]];
    }
}
- (void)loadMoreData{
    NSLog(@"loadMoreData");
    if (self.delegate && [self.delegate respondsToSelector:@selector(loadMorePersonListWithKey:)]) {
        [self.delegate loadMorePersonListWithKey:self.searchKey];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView){
        self.isDraging = YES;
    }
 
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.tableView){
        self.isDraging = NO;
    }
}

- (void)updateRefreshFooterState{
//    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

- (void)showBindVC:(RPBaseViewController *)bindVC delegate:(id<HomePageCommentViewDelegate>)delegate{
   
    self.delegate = delegate;
    
    [bindVC.view addSubview:self];
    [bindVC addChildViewController:self.commentListVC];
    [bindVC addChildViewController:self.replyListVC];
   
    if (self.platformType == XHPageDetailPlatformTypeBeginText) {
        self.containView.hidden = YES;
        [self beginTF];
    }else if (self.platformType == XHPageDetailPlatformTypeShowReply || self.platformType == XHPageDetailPlatformTypeMessageReply){
        self.containView.hidden = NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.containView.cl_y = kScreenH * 0.2;
        } completion:^(BOOL finished) {
            if (finished) {
                self.backImgView.hidden = YES;
                self.backBtn.hidden = YES;
                
                self.removeImgView.hidden = NO;
                self.removeBtn.hidden = NO;
            
                [self.scrollView setContentOffset:CGPointMake(kScreenW, 0) animated:NO];
                // 修改状态
                self.type = XHCommentTypeReply;
                self.inputPlaceLb.text = @"回复评论";
                self.bottomPlaceLb.text = @"回复评论";
                // 设置标题
                self.commentCountLb.text = @"";
            }
        }];
        
    }else{
        self.containView.hidden = NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.containView.cl_y = kScreenH * 0.2;
        }];
    }
}
- (void)dismiss{
    
    self.backgroundColor = RGBA(0, 0, 0, 0);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(dismissCommentView)]) {
        [self.delegate dismissCommentView];
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        self.cl_y = kScreenH;
    } completion:^(BOOL finished) {
        if (finished) {
            [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [self removeFromSuperview];
        }
    }];
}
- (void)aboutMethod{
    
    
    NSRange range = self.inputTextView.selectedRange;
    
    if (self.inputTextView.text.length >= 80) {
        [WHToast showMessage:@"已超过字数上限" duration:2 finishHandler:nil];
        return;
    }
    self.location = range.location;

    if (range.length != 0) {
        NSMutableString *string = [NSMutableString stringWithString:self.inputTextView.text];
        [string replaceCharactersInRange:range withString:@""];
        [string insertString:@"@" atIndex:range.location];
        self.inputTextView.text = string;
    }
    
    // 这里要处理一下
    if (self.locationDict.count > 0) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel *_Nonnull obj, BOOL * _Nonnull stop) {
            NSNumber *loc = key;
            // 保存到map的集合下标
            NSRange newRange = NSMakeRange(key.intValue,obj.realName.length + 1);
            if (range.length > 0) {
                if (NSLocationInRange(range.location,newRange) || NSLocationInRange(newRange.location,range)) {
                    NSLog(@"111");
                }else{
                    if (NSMaxRange(newRange) > range.location) {
                        [dict setObject:obj forKey:@(key.intValue - range.length + 1)];
                    }else{
                        [dict setObject:obj forKey:key];
                    }
                }
                
            }else{
                // 判断当前坐标小于map集合中的坐标(插入老数据前面)
                if (range.location >= newRange.location + newRange.length) {
                    [dict setObject:obj forKey:loc];
                    if (range.location == newRange.location + newRange.length) {
                        self.insertRang = NSMakeRange(range.location,1);
                    }
                }else if (range.location <= newRange.location) {
                    loc = @(key.intValue+1);
                    [dict setObject:obj forKey:loc];
                }else if(range.location > newRange.location || range.location <= newRange.length){
                    self.insertRang = NSMakeRange(newRange.location,newRange.length+1);
                }else{
                    [dict setObject:obj forKey:loc];
                }
            }
        }];
        self.locationDict = dict;
    }
 
    
    self.isSearch = YES;

    if (range.length == 0) {
        NSMutableString *content = [NSMutableString stringWithString:self.inputTextView.text];
        [content insertString:@"@" atIndex:range.location];
        self.inputTextView.text = content;
    }

    [self.inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.inputTextView.text.length)];
    [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, UserInfoModel * _Nonnull obj, BOOL * _Nonnull stop) {
        [self.inputTextView.textStorage addAttributes:@{NSForegroundColorAttributeName:RPAppManager.themColor} range:NSMakeRange(key.intValue, obj.realName.length + 1)];
    }];

    
    self.inputTextView.selectedRange = NSMakeRange(range.location + 1, 0);
    self.insertRang = NSMakeRange(range.location, 0);
    self.inputPlaceLb.hidden = YES;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(getCommentPersonListWithKey:)]) {
        [self startHeaderRefresh];
        [self.delegate getCommentPersonListWithKey:@"@"];
        self.tableView.contentOffset = CGPointZero;
    }
    self.searchKey = @"@";
    self.lastText = @"";
    self.isChinese = NO;
    self.markRangeLoc = NSMakeRange(0, 0);

}

- (void)coverMethod{
    // 清空相关内容
    [self resetResultBindViewData];
    
    [self.inputTextView endEditing:YES];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.inputView.cl_y = kScreenH;
    } completion:^(BOOL finished) {
        if (finished) {
            self.coverView.hidden = YES;
            if (self.platformType == XHPageDetailPlatformTypeBeginText) {
                [self dismiss];
            }
        }
    }];
}

- (void)backMethod{
    [self dismiss];
}
- (void)removeMethod{
    self.removeBtn.hidden = YES;
    self.removeImgView.hidden = YES;
    
    self.backBtn.hidden = NO;
    self.backImgView.hidden = NO;
    
    // 置空对象
    self.replyListVC.lastReplyModel.id = @0;
    
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    self.type = XHCommentTypeComment;
    self.inputPlaceLb.text = @"快来发布你的评论…";
    self.bottomPlaceLb.text = @"快来发布你的评论…";
    
    self.commentCountLb.text = [NSString stringWithFormat:@"%ld条评论",(long)self.commentCount];
}

- (void)sendMethod{
    
    if ([self.inputTextView.text isSpaceString] || self.inputTextView.text.length == 0) {
        [WHToast showMessage:@"内容不能为空" duration:2 finishHandler:nil];
        return;
    }
    
    [self endEditing:YES];
    
    __block NSString *str = self.inputTextView.text;
    
    NSArray *afterSortKeyArray = [self.locationDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult result = [obj1 compare:obj2];
        return result;
    }];
    
    NSMutableArray *users = [NSMutableArray array];
    
    __block NSInteger replacingLength = 0;
    [afterSortKeyArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UserInfoModel *userInfo = [self.locationDict objectForKey:obj];
        // 真实名字减去用户id 前进几位、后退几位
        if (idx == 0) {
            str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"@%@",userInfo.realName] withString:[NSString stringWithFormat:@"{%@}",userInfo.id] options:0 range:NSMakeRange(obj.intValue,userInfo.realName.length + 1)];
        }else{
            str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"@%@",userInfo.realName] withString:[NSString stringWithFormat:@"{%@}",userInfo.id] options:0 range:NSMakeRange(obj.intValue - replacingLength ,userInfo.realName.length + 1)];
        }
        [users addObject:userInfo];
        // 每次替换增加改变的数字
        replacingLength = replacingLength + userInfo.realName.length - userInfo.id.stringValue.length - 1;
    }];
    
    if (self.type == XHCommentTypeReply) {
        // 判断是在评论页回复还是回复页回复
        if (!self.removeImgView.hidden) {
            [self.replyListVC sendReplyMessage:str originalMessage:self.inputTextView.text userInfoList:users commentId:self.commentId];
        }else{
            [self.commentListVC sendReplyMessage:str originalMessage:self.inputTextView.text userInfoList:users commentId:self.commentId];
        }
    }
    if (self.type == XHCommentTypeComment) {
        [self.commentListVC sendCommentMessage:str originalMessage:self.inputTextView.text userInfoList:users];
    }
    // 置空内容

    // 重置搜索相关页面
    [self resetResultBindViewData];
    [UIView animateWithDuration:0.25 animations:^{
        self.inputView.cl_y = kScreenH;
    } completion:^(BOOL finished) {
        if (finished) {
            self.coverView.hidden = YES;
            if (self.containView.hidden) {
                self.containView.hidden = NO;
                self.platformType = XHPageDetailPlatformTypeShowComment;
                [UIView animateWithDuration:0.25 animations:^{
                    self.containView.cl_y = kScreenH * 0.2;
                }];
            }
        }
    }];
}

- (void)registNote{
    //监听键盘frame改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //添加键盘消失监听事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputModeDidChange:) name:UITextInputCurrentInputModeDidChangeNotification object:nil];
}

- (void)inputModeDidChange:(NSNotification *)note{
    self.isDictation = NO;
    if ([[[UIApplication sharedApplication]textInputMode].primaryLanguage isEqualToString:@"dictation"]) {
        self.isDictation = YES;
        self.dictationRange = self.inputTextView.selectedRange;
    }
}

//键盘即将弹出
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度 keyboardHeight
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    [UIView animateWithDuration:0.25 animations:^{
        self.inputView.cl_y = kScreenH - keyboardRect.size.height - self.inputView.cl_height;
        self.resultView.cl_y = CGRectGetMinY(self.inputView.frame) - kScreenW * 0.45;

    }];
}

- (void)beginTF{
     self.inputPlaceLb.hidden = self.inputTextView.text.length > 0;
     if (!self.removeImgView.hidden) {
         self.type = XHCommentTypeReply;
         self.inputPlaceLb.text = @"回复评论";
     }else{
         self.type = XHCommentTypeComment;
         self.inputPlaceLb.text = @"快来发布你的评论…";
     }
     [self showInputTextView];
}

- (void)showInputTextView{
    self.coverView.hidden = NO;
    [self.inputTextView becomeFirstResponder];
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.containView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.containView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.containView.layer.mask = maskLayer;
    
    UIBezierPath *maskPath1 = [UIBezierPath bezierPathWithRoundedRect:self.resultView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer1 = [[CAShapeLayer alloc] init];
    maskLayer1.frame = self.resultView.bounds;
    maskLayer1.path = maskPath1.CGPath;
    self.resultView.layer.mask = maskLayer1;

    
    [self addShadowToView:self.bottomView withColor:RGBA(0, 0, 0, 0.5)];
}


- (void)refreshUsers:(NSMutableArray *)users{
    
    [self.userArray removeAllObjects];

    [self.userArray addObjectsFromArray:users];

    if (self.userArray.count == 0) {
        self.resultView.hidden = YES;
    }else{
        self.resultView.hidden = NO;
    }
    self.resultView.cl_y = CGRectGetMinY(self.inputView.frame) - kScreenW * 0.45;
    
    [self stopHeaderRefresh];
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
    
    [self.tableView reloadData];
}


- (void)stopHeaderRefresh{
    [self.headerLoadingView stopAnimationLoading];
    self.resultRefreshHeaderView.hidden = YES;
}

- (void)startHeaderRefresh{
    [self.headerLoadingView startLoading];
    [self.userArray removeAllObjects];
    [self.tableView reloadData];
    self.resultRefreshHeaderView.hidden = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.userArray.count == 0;
    return self.userArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    HomePageCommentFollowCell *cell = [HomePageCommentFollowCell cellWithTableView:tableView];
    [cell setModel:self.userArray[indexPath.row]];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64.0f;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UserInfoModel *userInfo = self.userArray[indexPath.row];
    [self resetResultView];
    
    NSString *text = [self.inputTextView.text substringWithRange:NSMakeRange(self.location,self.inputTextView.selectedRange.location - self.location)];
    NSString *content = [self.inputTextView.text stringByReplacingOccurrencesOfString:text withString:@"" options:0 range:NSMakeRange(self.location,self.inputTextView.selectedRange.location - self.location)];
    
    NSString *appendStr = [content substringWithRange:NSMakeRange(self.location, content.length - self.location)];
    // @前面字符串
    NSString *newStr = [content substringWithRange:NSMakeRange(0, self.location)];
    
    if ([NSString stringWithFormat:@"%@@%@%@",newStr,userInfo.realName,appendStr].length > 80) {
        [WHToast showMessage:@"已超过字数上限" duration:2 finishHandler:nil];
        return;
    }
    
    NSMutableString *result = [NSMutableString stringWithString:content];
    [result insertString:[NSString stringWithFormat:@"@%@",userInfo.realName] atIndex:self.location];
    self.inputTextView.text = result;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber  *_Nonnull key, UserInfoModel *_Nonnull obj, BOOL * _Nonnull stop) {
        NSNumber *location = key;
        if (key.intValue >= self.location) {
            if ([text isEqualToString:@"@"]) {
                location = @(key.intValue + userInfo.realName.length);
            }else{
                location = @(key.intValue + userInfo.realName.length - text.length+1);
            }
        }
        [dict setObject:obj forKey:location];
    }];
    self.locationDict = dict;
    [self.locationDict setObject:userInfo forKey:@(self.location)];
    [self changeTextStatus];
    self.markRangeLoc = NSMakeRange(0, 0);
    
    self.isChinese = NO;
    
    self.inputTextView.selectedRange = NSMakeRange(self.location + userInfo.realName.length + 1, 0);
    
    self.location = -1;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    self.markRangeLoc = NSMakeRange(0, 0);
    
    self.isDelete = NO;
    
    self.lastSelectedRange = textView.selectedRange;
    
    NSMutableString *string = [NSMutableString stringWithString:textView.text];
    
    [string replaceCharactersInRange:range withString:text];
     
    if (string.length > 80) {
        [WHToast showMessage:@"已超过字数上限" duration:2 finishHandler:nil];
        return NO;
    }
    
    if ([text isEqualToString:@"@"]) {
        self.location = range.location;
        self.insertRang = NSMakeRange(range.location, 1);
        // 这里要处理一下
        if (self.locationDict.count > 0) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel *_Nonnull obj, BOOL * _Nonnull stop) {
                NSNumber *loc = key;
                NSRange newRange = NSMakeRange(key.intValue,obj.realName.length + 1);
                // 判断当前坐标小于map集合中的坐标(插入老数据前面)
                if (range.location >= newRange.location + newRange.length) {
                    [dict setObject:obj forKey:loc];
                    self.insertRang = NSMakeRange(range.location,1);
                }else if (range.location <= newRange.location) {
                    self.insertRang = NSMakeRange(range.location,1);
                }else if(range.location > newRange.location || range.location <= newRange.length){
                    self.insertRang = NSMakeRange(newRange.location,newRange.length+1);
                    [textView.textStorage removeAttribute:NSForegroundColorAttributeName range:newRange];
                }
            }];
        }
        self.isSearch = YES;
        return YES;
    }else if ([text isEqualToString:@""]) {
        self.isDelete = YES;
        NSRange selectRange = textView.selectedRange;
        if (selectRange.length > 0) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel  *_Nonnull obj, BOOL * _Nonnull stop) {
                NSRange newRange = NSMakeRange(key.intValue,obj.realName.length + 1);
                // 包含对象
                if (NSLocationInRange(newRange.location, range) || (range.location > newRange.location && range.location < NSMaxRange(newRange))) {
                    
                }else{
                    if (newRange.location > selectRange.location) {
                        NSInteger new = key.intValue - selectRange.length;
                        [dict setObject:obj forKey:@(new)];
                    }else{
                        [dict setObject:obj forKey:key];
                    }
                }
            }];
            self.locationDict = dict;
            NSMutableString *string = [NSMutableString stringWithString:textView.text];
            [string replaceCharactersInRange:selectRange withString:@""];
            textView.text = string;
            [self changeTextStatus];
            self.inputTextView.selectedRange = NSMakeRange(self.lastSelectedRange.location, 0);
            // 隐藏键盘
            [self resetResultView];
            
            return NO;
        }
        // 判断高亮选择一段
        NSMutableString *string = [NSMutableString stringWithString:textView.text];
        __block BOOL inAt = NO;
        __block NSInteger index = range.location;
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel *_Nonnull obj, BOOL * _Nonnull stop) {
            NSRange newRange = NSMakeRange(key.intValue,obj.realName.length + 1);
            if ((NSLocationInRange(range.location, newRange) && selectRange.location != newRange.location)) {
                [string replaceCharactersInRange:newRange withString:@""];
                inAt = YES;
                index = newRange.location;
                *stop = YES;
            }else{
                if (newRange.location >= range.location && range.length != 0) {
                    [dict setObject:obj forKey:@(key.intValue - range.length)];
                }else{
                    [dict setObject:obj forKey:key];
                }
            }
        }];
        if (inAt){
            textView.text = string;
            [self updateLocationWithRemoveLocation:index];
            [self changeTextStatus];
            
            self.inputTextView.selectedRange = NSMakeRange(index, 0);
            
            return NO;
        }else{
            if (self.lastText.length == 0) {
                self.locationDict = dict;
            }
            self.insertRang = NSMakeRange(range.location, 0);
            return YES;
        }
    }else{
        self.insertRang = NSMakeRange(range.location, text.length);
        return YES;
    }
    
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    
    __block BOOL InRange = NO;
    
    if (self.isDictation) {
        [self.locationDict removeAllObjects];
    }else{
        if ([textView markedTextRange] == nil && !self.isDelete) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel * _Nonnull obj, BOOL * _Nonnull stop) {
            if (self.isChinese) {
                [dict setObject:obj forKey:key];
            }else{
                NSRange newRange = NSMakeRange(key.intValue, obj.realName.length + 1);
                if (textView.selectedRange.length != 0) {
                    
                }else{
                    // 这里判断是否是键盘转换
                    if (NSMaxRange(self.markRangeLoc) > 0) {
                        // 获取原本的索引位置
                        if (textView.selectedRange.location > NSMaxRange(newRange)) {
                            [dict setObject:obj forKey:key];
                        }else{
                            NSInteger oldIndex = key.intValue - self.markRangeLoc.length;
                            // 判断光标是否包含了这个位置
                            [dict setObject:obj forKey:@(oldIndex + textView.selectedRange.location - self.markRangeLoc.location)];
                        }

                    }else{
                        if (self.insertRang.location >= NSMaxRange(newRange)) {
                            [dict setObject:obj forKey:key];
                        }else if ((self.insertRang.location > newRange.location &&
                                   NSMaxRange(self.insertRang) <= NSMaxRange(newRange)) || (self.lastSelectedRange.location < newRange.location && NSMaxRange(self.lastSelectedRange) > newRange.location)){
                        }else{
                            
                            if (self.insertRang.location <= newRange.location) {
                                // 判断插入位置和初始位置是同一个则不加入map
                                if (self.insertRang.location == newRange.location) {
                                    // 判断选中位置是否包含了高亮位置
                                    if ((self.lastSelectedRange.location >= key.intValue || NSMaxRange(self.lastSelectedRange) <= NSMaxRange(newRange)) && self.lastSelectedRange.length > 0) {
                                    }else if((NSMaxRange(self.lastSelectedRange) <= key.intValue || NSMaxRange(self.lastSelectedRange) > NSMaxRange(newRange))) {
                                        // 文字位置没有发生变化
                                        if (self.inputTextView.selectedRange.location == self.lastSelectedRange.location) {
                                            self.insertRang = self.lastSelectedRange;
                                            [dict setObject:obj forKey:key];
                                        }else{
                                            if (NSMaxRange(self.markRangeLoc) < NSMaxRange(textView.selectedRange) && NSMaxRange(self.markRangeLoc) > 0) {
                                                [dict setObject:obj forKey:@(key.intValue - NSMaxRange(self.markRangeLoc) + NSMaxRange(textView.selectedRange))];
                                            }else{
                                                [dict setObject:obj forKey:@(key.intValue + self.insertRang.length - self.lastSelectedRange.length)];
                                            }
                                        }

                                    }
                                }else if(key.intValue != self.lastSelectedRange.location){
                                    // insert 插入的文字的位置长度 lastSelectedRange 高亮选择部分 差值就是这次添加的内容长度
                                    if (self.inputTextView.selectedRange.location == self.lastSelectedRange.location) {
                                        if (NSMaxRange(self.markRangeLoc) < NSMaxRange(textView.selectedRange) && NSMaxRange(self.markRangeLoc) > 0) {
                                            [dict setObject:obj forKey:@(key.intValue - NSMaxRange(self.markRangeLoc) + NSMaxRange(textView.selectedRange))];
                                        }else{
                                            [dict setObject:obj forKey:key];
                                        }
                                        self.insertRang = self.lastSelectedRange;
                                    }else{
                                        if (NSMaxRange(self.markRangeLoc) < NSMaxRange(textView.selectedRange) && NSMaxRange(self.markRangeLoc) > 0) {
                                            [dict setObject:obj forKey:@(key.intValue - NSMaxRange(self.markRangeLoc) + NSMaxRange(textView.selectedRange))];
                                        }else{
                                            [dict setObject:obj forKey:@(key.intValue + self.insertRang.length - self.lastSelectedRange.length)];
                                        }
                                    }
                                }
                            }else{
                                [dict setObject:obj forKey:key];
                            }
                        }
                    }
                }
            }
        }];
        if (!self.isChinese) {
            self.markRangeLoc = NSMakeRange(0, 0);
        }
        self.lastText = @"";
        self.isChinese = NO;
  
        self.locationDict = dict;
    }else{
        self.isChinese = YES;
        UITextPosition* beginning = textView.beginningOfDocument;
        UITextRange *selectedRange = [textView markedTextRange];
        NSString * newText = [textView textInRange:selectedRange];
        NSInteger location = [textView offsetFromPosition:beginning toPosition:selectedRange.start];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        self.markRangeLoc = NSMakeRange(location, newText.length);
        
        [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber  *_Nonnull key, UserInfoModel * _Nonnull obj, BOOL * _Nonnull stop) {
          
            NSRange newRange = NSMakeRange(key.intValue, obj.realName.length + 1);
            // 多选内容情况下
            if (self.lastSelectedRange.length > 0 && self.lastText.length != newText.length) {
                NSInteger max = self.lastSelectedRange.length - newText.length;
                if (NSLocationInRange(self.lastSelectedRange.location, newRange) || NSLocationInRange(newRange.location,self.lastSelectedRange)) {
                    NSLog(@"包含了");
                }else{
                    if (newRange.location >= self.lastSelectedRange.location && newRange.location >= NSMaxRange(self.lastSelectedRange)) {
                        [dict setObject:obj forKey:@(key.intValue - max)];
                    }else{
                        // 判断高亮的位置
                        if (newRange.location > self.lastSelectedRange.location) {
                            // 判断长度是否包含了newRange
                            if (NSMaxRange(newRange) > self.lastSelectedRange.location) {
                                [dict setObject:obj forKey:key];
                            }
                        }else if (newRange.location < self.lastSelectedRange.location){
                            if (NSMaxRange(newRange) <= self.lastSelectedRange.location) {
                                [dict setObject:obj forKey:key];
                            }
                        }
                    }
                }
            }else{
                if (location == newRange.location) {
                    if (!NSEqualRanges(self.insertRang, self.lastSelectedRange)) {
                        [dict setObject:obj forKey:@(key.intValue + newText.length)];
                    }else{
                        InRange = YES;
                    }
                }else{
                    if (NSMaxRange(newRange) <= location) {
                        [dict setObject:obj forKey:key];
                    }else{
                        if (NSLocationInRange(location, newRange)) {
                            InRange = YES;
                        }else{
                            // 当前未设置 大于插入的位置
                            if (NSMaxRange(newRange) > location + newText.length) {
                                // 判断上一个是否插入
                                if (InRange) {
                                    if (NSEqualRanges(self.insertRang, self.lastSelectedRange)) {
                                        [dict setObject:obj forKey:key];
                                    }else{
                                        [dict setObject:obj forKey:@(key.intValue - self.lastText.length + newText.length)];
                                    }
                                }else{
                                    if (self.insertRang.location == self.lastSelectedRange.location && self.insertRang.length > self.lastSelectedRange.length) {
                                        [dict setObject:obj forKey:@(key.intValue - self.lastText.length + newText.length)];
                                    }else{
                                        [dict setObject:obj forKey:@(key.intValue + (newText.length - self.lastText.length))];
                                    }
                                   
                                }
                            }
                        }
                    }
                }
            }
        }];
        
        if (![self.lastText isEqualToString:newText]) {
            self.isChinese = YES;
        }else{
            self.isChinese = NO;
        }
        self.lastText = newText;
        self.locationDict = dict;
        }
    }
    if (textView.text.length == 0) {
        [self.locationDict removeAllObjects];
    }

    self.inputPlaceLb.hidden = textView.text.length > 0;
        
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    NSString *toBeString = textView.text;
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > 80){
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:80];
            if (rangeIndex.length == 1){
                textView.text = [toBeString substringToIndex:80];
                if (toBeString.length > 80) {
                    [WHToast showMessage:@"已超过字数上限" duration:2 finishHandler:nil];
                    return;
                }
            }else{
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0,80)];
                textView.text = [toBeString substringWithRange:rangeRange];
           
                if (rangeRange.length < toBeString.length) {
                    [WHToast showMessage:@"已超过字数上限" duration:2 finishHandler:nil];
                    return;
                }
            }
        }
    }
    
    if (textView.text.length != 0) {
        if (self.isSearch) {
            if (self.location <= textView.selectedRange.location) {
                NSString *text = [textView.text substringWithRange:NSMakeRange(self.location,textView.selectedRange.location - self.location)];
                if (text.length > 0) {
                    if ([text isEqualToString:@"@"]) {
                        if (self.delegate && [self.delegate respondsToSelector:@selector(getCommentPersonListWithKey:)]) {
                            [self startHeaderRefresh];
                            [self.delegate getCommentPersonListWithKey:@"@"];
                            self.tableView.contentOffset = CGPointZero;
                        }
                        self.searchKey = @"@";
                    }else{
                        NSString *str = [text substringFromIndex:1];
                        if (self.delegate && [self.delegate respondsToSelector:@selector(getCommentPersonListWithKey:)]) {
                            [self startHeaderRefresh];
                            [self.delegate getCommentPersonListWithKey:str];
                        }
                        self.searchKey = str;
                    }
                }else{
                    [self textChangeResetView];
                }
            }
        }
    }else{
        [self textChangeResetView];
    }
    
    [textView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, textView.text.length)];
    [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, UserInfoModel * _Nonnull obj, BOOL * _Nonnull stop) {
        [textView.textStorage addAttributes:@{NSForegroundColorAttributeName:RPAppManager.themColor} range:NSMakeRange(key.intValue, obj.realName.length + 1)];
    }];
 
    
    
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    if (self.isSearch && textView.selectedRange.location <= self.location) {
        [self resetResultView];
    }
    if (self.isDictation) {    
        self.dictationRange = NSMakeRange(self.dictationRange.location, textView.selectedRange.location - self.dictationRange.location);
    }
}

- (void)textChangeResetView{
    self.isSearch = NO;
    [self.userArray removeAllObjects];
    self.resultView.hidden = YES;
    self.resultView.cl_y = CGRectGetMinY(self.inputView.frame) - kScreenW * 0.45;
    [self.tableView reloadData];
}


- (void)changeTextStatus{
    
    [self.inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.inputTextView.text.length)];
    [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, UserInfoModel * _Nonnull obj, BOOL * _Nonnull stop) {
        [self.inputTextView.textStorage addAttributes:@{NSForegroundColorAttributeName:RPAppManager.themColor} range:NSMakeRange(key.intValue, obj.realName.length + 1)];
    }];
    self.inputPlaceLb.hidden = self.inputTextView.text.length > 0;
}


- (void)updateLocationWithRemoveLocation:(NSInteger)location{
    UserInfoModel *userInfo = [self.locationDict objectForKey:@(location)];
    [self.locationDict removeObjectForKey:@(location)];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [self.locationDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *_Nonnull key, UserInfoModel *_Nonnull obj, BOOL * _Nonnull stop) {
        NSNumber *result = key;
        if (key.intValue >= location) {
            result = @(key.intValue - (userInfo.realName.length + 1));
        }
        [dict setObject:obj forKey:result];
    }];
    self.locationDict = dict;
}



#pragma - 初始化页面
- (void)resetResultBindViewData{
 
    // 清空@索引位置
    [self.locationDict removeAllObjects];
    // 清空搜索列表
    [self.userArray removeAllObjects];
    
    [self.tableView reloadData];
    // 输入框内容置空
    self.inputTextView.text = @"";
    
    [self resetResultView];

}

- (void)resetResultView{
    self.isSearch = NO;
    // 位置归位
    // 停止相关刷新动画
    [self stopHeaderRefresh];
    
    self.resultView.cl_y = CGRectGetMinY(self.inputView.frame) - kScreenW * 0.45;
    // 隐藏
    self.resultView.hidden = YES;

}


#pragma mark - 新增阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    theView.layer.shadowColor = theColor.CGColor;
    theView.layer.shadowOffset = CGSizeMake(0,0);
    theView.layer.shadowOpacity = 0.1;
    theView.layer.shadowRadius = 1;
// 单边阴影 顶边
    float shadowPathWidth = theView.layer.shadowRadius;
    CGRect shadowRect = CGRectMake(0, 0, theView.bounds.size.width, shadowPathWidth);
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:shadowRect];
    theView.layer.shadowPath = path.CGPath;
}

@end
